package com.goodjia.phase1module4;

public class TrainTicketThreadTest extends Thread {

    private int ticketCount;// 用于描述火车票剩余票数
    private static LockFlag lockFlag = new LockFlag();// 继承Thread类的方式加锁 需要的这个类对象必须是static声明的 保证整个类共享一个对象否则无法锁住

    public TrainTicketThreadTest() {
    }

    public TrainTicketThreadTest(int ticketCount) {
        this.ticketCount = ticketCount;
    }

    public int getTicketCount() {
        return ticketCount;
    }

    public void setTicketCount(int ticketCount) {
        this.ticketCount = ticketCount;
    }

    @Override
    public void run() {
        System.out.println("线程" + Thread.currentThread().getName() + "已启动");
        synchronized (lockFlag) {
            int temp = getTicketCount();
            if (temp > 0) {
                temp -= 1;
                System.out.println("正在出票...请稍后");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("出票成功!");
                System.out.println("请取走您的票");
            } else {
                System.out.println("余票不足请等待");
            }
            setTicketCount(temp);// 重新设置余票数量
            System.out.println("剩余票数为：" + getTicketCount());
            System.out.println("--------------------");
        }
    }

    public static void main(String[] args) {

        // 直接继承Thread类的创建方式创建三个线程
        TrainTicketThreadTest thread1 = new TrainTicketThreadTest(100);
        TrainTicketThreadTest thread2 = new TrainTicketThreadTest(100);
        TrainTicketThreadTest thread3 = new TrainTicketThreadTest(100);

        // 这种方式直接启动线程
        thread1.start();
        thread2.start();
        thread3.start();

        // 主线程等待三个线程结束
        System.out.println("主线程等待中....");
        try {
            thread1.join();
            thread2.join();
            thread3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("剩余票数为: " + thread1.getTicketCount());

    }
}

class LockFlag {}
